package com.wiim.nhapnhap;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.util.Base64;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.wiim.common.ConstantValue;
import com.wiim.common.FragmentFactory;
import com.wiim.common.Utilities;
import com.wiim.interfaceapp.PassDataInterface;
import com.wiim.interfaceapp.onImageSet;
import com.wiim.libs.DatePickerDialogFragment;
import com.wiim.model.CalendarModel;
import com.wiim.model.UserModel;

@SuppressWarnings("unused")
public class CustomFragmentActivity extends FragmentActivity implements PassDataInterface {

	protected ArrayList<Integer> mListView;

	private Map<String, Object> passData;

	private static final String DATE_FRAGMENT = "date_fragment";

	private static final String MAP_FRAGMENT = "map_fragment";

	private FrameLayout frMain;

	private RelativeLayout pdBar;

	private ProgressBar pdBarMain;

	public Boolean isShowDialog = false;

	protected Fragment mFragment;

	public static Boolean isShowProgressBar = false;

	protected Boolean isOnActivityResult = false;

	public Boolean clearCasch = false;

	public static DisplayImageOptions options;

	public static ImageLoader imageLoader2;

	private int mTitleRes;
	protected Fragment mFrag;

	private Bundle savedInstanceState;

//	public CustomFragmentActivity(int titleRes) {
//		System.out.println("tinhvc mTitleRes: " + mTitleRes);
//		mTitleRes = titleRes;
//	}

	@SuppressWarnings("static-access")
	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// TODO Auto-generated method stub
		if (this.mListView == null) {
			this.mListView = new ArrayList<Integer>();
		}

		this.frMain = (FrameLayout) this.findViewById(R.id.frMain);
		this.pdBar = (RelativeLayout) this.findViewById(R.id.pdBar);
		this.pdBarMain = (ProgressBar) this.findViewById(R.id.pdBarMain);
		this.clearCasch = Utilities.getGlobalVariable(this).clearCase;

		if (Utilities.getGlobalVariable(CustomFragmentActivity.this).isHavePush == false) {
			getSettingPush(CustomFragmentActivity.this);
		}

		imageLoader2 = com.nostra13.universalimageloader.core.ImageLoader.getInstance();

		Utilities.getGlobalVariable(this).initImageLoader(this, imageLoader2);
		// options = new
		// DisplayImageOptions.Builder().showStubImage(R.drawable.photo_none).showImageForEmptyUri(R.drawable.photo_none).showImageOnFail(R.drawable.photo_none).cacheInMemory().cacheOnDisc().bitmapConfig(Bitmap.Config.RGB_565).build();

		options = new DisplayImageOptions.Builder().showStubImage(R.drawable.photo_none).showImageForEmptyUri(R.drawable.photo_none).showImageOnFail(R.drawable.photo_none).cacheInMemory()
				.cacheOnDisc().bitmapConfig(Bitmap.Config.RGB_565).build();
		if (clearCasch) {
			imageLoader2.clearDiscCache();
			imageLoader2.clearMemoryCache();
		}
	}

//	public void setSlidingMenu(Fragment fragment, Boolean isShowMenu) {
//		setTitle(mTitleRes);
//
//		// set the Behind View
//		setBehindContentView(R.layout.sliding_menu_view_root_layout);
//		if (savedInstanceState == null) {
//			FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
//			mFrag = fragment;
//			t.replace(R.id.menu_frame, mFrag);
//			t.commit();
//		} else {
//			mFrag = (ListFragment) this.getSupportFragmentManager().findFragmentById(R.id.menu_frame);
//		}
//
//		// customize the SlidingMenu
//		SlidingMenu sm = getSlidingMenu();
//		sm.setShadowWidthRes(R.dimen.margin_15);
//		sm.setShadowDrawable(R.drawable.shadow);
//		sm.setBehindOffsetRes(R.dimen.margin_60);
//		sm.setFadeDegree(0.35f);
//		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
//		sm.setSlidingEnabled(isShowMenu);
////		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//	}

	public void getSettingPush(Context context) {
		Utilities.getGlobalVariable(this).isHavePush = true;
		/**
		 * Function get push from server
		 */
	}

	public void resetListFragment() {
		while (mListView.size() > 0) {
			mListView.remove(mListView.size() - 1);
		}
	}

	/**
	 * get string from bitmap
	 * 
	 * @param bitmap
	 * @param check
	 * @return
	 */
	public String getStringFromBitmap(final Bitmap bitmap, final String check) {

		String s = null;
		byte[] bytes = null;
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			if (check.equalsIgnoreCase("PNG")) {
				bitmap.compress(Bitmap.CompressFormat.PNG, 70, baos);
			} else {
				bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);
			}
			bytes = baos.toByteArray();
			s = Base64.encodeToString(bytes, 1);
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return s;
	}

	// Read bitmap
	public Bitmap getBitmapFromURI(Context cont, Uri selectedImage) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inSampleSize = 4;
		Bitmap bm = null;
		AssetFileDescriptor fileDescriptor = null;
		try {
			fileDescriptor = cont.getContentResolver().openAssetFileDescriptor(selectedImage, "r");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, opt);
				fileDescriptor.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bm;
	}

	/**
	 * end
	 */

	public void startFragment(final int key) {
		// && (key != ConstantValue.SETTING_SIGNUP_FRAGMENT)
		if (!this.mListView.contains(key)) {
			this.mListView.add(key);
		}
		fragmentTransition(key);

	}

	public void replaceFragment(final int key, final Boolean isAnimation) {
		// && (key != ConstantValue.SETTING_SIGNUP_FRAGMENT)
		// // change release map to here
		// if (mFragment instanceof CustomGoogleMapFragment) {
		// releaseMap();
		// }
		if (!this.mListView.contains(key)) {
			this.mListView.add(key);
		}
		if (isAnimation) {
			this.flipit(key, true);
		} else {
			fragmentTransition(key);
		}
	}

	public void replaceFragmentPeer(final int key, final Boolean isAnimation, Boolean peer) {
		// && (key != ConstantValue.SETTING_SIGNUP_FRAGMENT)
		// // change release map to here
		// if (mFragment instanceof CustomGoogleMapFragment) {
		// releaseMap();
		// }

		if (peer) {
			if (!this.mListView.contains(key)) {
				this.mListView.add(key);
			}
		} else {
			this.mListView.add(key);
		}
		if (peer) {
			this.mListView.remove(mListView.size() - 1);
			this.mListView.add(key);
		}
		if (isAnimation) {
			this.flipit(key, true);
		} else {
			fragmentTransition(key);
		}
	}

	public void backToFragment(final int key, final Boolean isAnimation) {

		if (isAnimation) {
			this.flipit(key, false);
		} else {
			fragmentTransition(key);
		}

	}

	public void returnToFragment(final int key, final Boolean isAnimation) {

		for (int i = mListView.size() - 1; i >= 0; i--) {
			if (mListView.get(i) == key) {
				break;
			}
			mListView.remove(mListView.size() - 1);
		}

		if (isAnimation) {
			this.flipit(key, false);
		} else {
			fragmentTransition(key);
		}

	}

	FragmentTransaction fragmentTS;

	public void fragmentTransition(final int key) {
		System.gc();
		imageLoader2.stop();
		imageLoader2.clearMemoryCache();
		onFragmentChange();
		if (mFragment instanceof CustomGoogleMapFragment) {
			// releaseMap();
		}
		if (null != mFragment) {
			fragmentTS.remove(mFragment);
		}
		fragmentTS = this.getSupportFragmentManager().beginTransaction();
		mFragment = FragmentFactory.getFragmentByKey(key);
		// fragmentTS.setCustomAnimations(R.anim.slide_in_left,
		// R.anim.slide_out_right);
		fragmentTS.replace(R.id.frMain, mFragment);
		// fragmentTS.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
		fragmentTS.commitAllowingStateLoss();
	}

	public Fragment findFragment() {
		return mFragment;
	}

	/**
	 * Gets the picture.
	 */
	public void getPicture() {
		isOnActivityResult = true;
		this.startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), ConstantValue.UPLOAD_PHOTO);
	}

	public void showDatePickerDialog(Fragment fragment, Boolean isDatepicker) {
		if (!isShowDialog) {
			isShowDialog = true;
			DatePickerDialogFragment newFragment = new DatePickerDialogFragment(fragment, isDatepicker);
			newFragment.show(getSupportFragmentManager(), DATE_FRAGMENT);
		}
	}

	public Object getPassedValue(final String key) {

		// TODO Auto-generated method stub
		if (null != passData && passData.containsKey(key)) {
			return this.passData.get(key);
		}
		return -1;
	}

	public void setPassValue(final String key, final Object value) {

		// TODO Auto-generated method stub
		if (this.passData == null) {
			this.passData = new HashMap<String, Object>();
		}
		this.passData.put(key, value);

	}

	// public static Boolean isSignUpCompany = false;

	@Override
	public void onBackPressed() {
		if (this.mListView.size() > 1) {
			Boolean isAnimation = false;
			this.mListView.remove(this.mListView.size() - 1);
			this.backToFragment(this.mListView.get(this.mListView.size() - 1), isAnimation);
		} else {
			Utilities.showDialogExit(CustomFragmentActivity.this, "Nhấp Nhấp", "Bạn muốn đóng ứng dụng?", CustomFragmentActivity.this);
		}
		return;
	}

	/**
	 * Process display view after makeup
	 * 
	 */
	public void recycle(ImageView iv) {
		Drawable drawable = iv.getDrawable();
		if (drawable instanceof BitmapDrawable) {

			Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
			iv.setImageBitmap(null);
			iv.setImageDrawable(null);
			iv.postInvalidate();

			if (bitmap != null)
				bitmap.recycle();
			bitmap = null;
		}
	}

	private Boolean isRun = true;

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		isRun = true;
		isOnActivityResult = false;

	}

	/**
	 * dangtb view rotate animation
	 */
	private Interpolator accelerator = new AccelerateInterpolator();

	private Interpolator decelerator = new DecelerateInterpolator();

	private void flipit(final int key, final Boolean isForward) {

		float visToInvisFrom;
		float visToInvisTo;
		final float invisToVisFrom;
		final float invisToVisTo;
		if (isForward) {
			visToInvisFrom = 0f;
			visToInvisTo = 90f;
			invisToVisFrom = -90f;
			invisToVisTo = 0f;
		} else {
			visToInvisFrom = 0f;
			visToInvisTo = -90f;
			invisToVisFrom = 90f;
			invisToVisTo = 0f;
		}
		ObjectAnimator visToInvis = ObjectAnimator.ofFloat(this.frMain, "rotationY", visToInvisFrom, visToInvisTo);
		final ObjectAnimator invisToVis = ObjectAnimator.ofFloat(this.frMain, "rotationY", invisToVisFrom, invisToVisTo);
		invisToVis.setDuration(250);
		// invisToVis.setInterpolator(decelerator);
		visToInvis.setDuration(250);
		// visToInvis.setInterpolator(accelerator);
		visToInvis.addListener(new AnimatorListenerAdapter() {

			@Override
			public void onAnimationStart(final Animator animation) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onAnimationEnd(final Animator anim) {
				fragmentTransition(key);
				new Handler().postDelayed(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						invisToVis.start();
					}
				}, 1);
			}
		});
		invisToVis.addListener(new AnimatorListenerAdapter() {

			@Override
			public void onAnimationStart(final Animator animation) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onAnimationEnd(final Animator animation) {

			}

		});
		visToInvis.start();
	}

	public void showProgressBar() {
		pdBar.setVisibility(View.VISIBLE);
		frMain.setEnabled(false);
		isShowProgressBar = true;
		final InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		mgr.hideSoftInputFromWindow(frMain.getWindowToken(), 0);
	}

	public void hideProgressBar() {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				pdBar.setVisibility(View.GONE);
				frMain.setEnabled(true);
				isShowProgressBar = false;
			}
		});
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
		if (isShowProgressBar)
			return false;
		return super.dispatchTouchEvent(ev);
	}

	public static void saveObJectToFile(Object objectToWrite, Context con, String _fileName) {
		String fileName = _fileName;
		try {
			FileOutputStream fos = con.openFileOutput(fileName, Context.MODE_PRIVATE);
			ObjectOutputStream os;
			os = new ObjectOutputStream(fos);
			os.writeObject(objectToWrite);
			os.close();
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static UserModel readUserFromFile(Context con, String _fileName) {
		UserModel simpleClass = null;
		String fileName = _fileName;
		try {
			FileInputStream fis = con.openFileInput(fileName);
			ObjectInputStream is = new ObjectInputStream(fis);
			simpleClass = (UserModel) is.readObject();
			is.close();
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return simpleClass;
	}

	public static CalendarModel readCalendarFromFile(Context con, String _fileName) {
		CalendarModel simpleClass = null;
		String fileName = _fileName;
		try {
			FileInputStream fis = con.openFileInput(fileName);
			ObjectInputStream is = new ObjectInputStream(fis);
			simpleClass = (CalendarModel) is.readObject();
			is.close();
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return simpleClass;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		isRun = false;
		super.onPause();
		// releaseMap();
	}

	// /**
	// * Release mapview when not use
	// */
	// public void releaseMap() {
	// try {
	// FragmentTransaction trans =
	// getSupportFragmentManager().beginTransaction();
	// SupportMapFragment frag = ((SupportMapFragment)
	// this.getSupportFragmentManager().findFragmentById(R.id.mapMain));
	// if (null != frag) {
	// trans.remove(frag);
	// }
	// trans.commitAllowingStateLoss();
	// } catch (Throwable e) {
	// e.printStackTrace();
	// }
	// }

	public void onFragmentChange() {

	}

	/**
	 * [Explain the description for this method here].
	 * 
	 * @param requestCode
	 *            the request code
	 * @param resultCode
	 *            the result code
	 * @param data
	 *            the data
	 * @see android.app.Activity#onActivityResult(int, int,
	 *      android.content.Intent)
	 */
	@Override
	protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == ConstantValue.UPLOAD_PHOTO) {
				try {
					Uri selectedImageUri = data.getData();
					String selectedImagePath = getPath(selectedImageUri);
					((onImageSet) findFragment()).setimage(selectedImageUri, selectedImagePath);
				} catch (Exception e) {
					e.printStackTrace();
					this.calldialog();
				}
			} else if (requestCode == ConstantValue.UPLOAD_PHOTO_CAMERA) {
				try {
					String selectedImagePath = data.getStringExtra(ConstantValue.RESULT);
					((onImageSet) findFragment()).setimage(null, selectedImagePath);
				} catch (Exception e) {
					e.printStackTrace();
					this.calldialog();
				}
			}
		}
	}

	/**
	 * Calldialog.
	 */
	public void calldialog() {
		AlertDialog.Builder builder;
		builder = new AlertDialog.Builder(this);
		builder.setMessage("Your Selection is not a photo").setNeutralButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(final DialogInterface dialog, final int id) {
				// Do nothing.\

			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	/**
	 * Gets the path.
	 * 
	 * @param uri
	 *            the uri
	 * @return the path
	 */
	@SuppressWarnings("deprecation")
	public String getPath(final Uri uri) {

		String[] projection = { MediaStore.Images.Media.DATA };

		Cursor cursor = this.managedQuery(uri, projection, null, null, null);

		int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

		cursor.moveToFirst();

		return cursor.getString(columnIndex);

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		isRun = false;
		super.onStop();
	}

	private Boolean isCallingFace = false;

	private Bitmap getBitmapFromAsset(String strName) throws IOException {
		AssetManager assetManager = getAssets();

		InputStream istr = assetManager.open(strName);
		Bitmap bitmap = BitmapFactory.decodeStream(istr);

		return bitmap;
	}

//	@Override
//	public boolean onOptionsItemSelected(MenuItem item) {
//		switch (item.getItemId()) {
//		case android.R.id.home:
//			toggle();
//			return true;
//		}
//		return super.onOptionsItemSelected(item);
//	}
//
//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
////		getSupportMenuInflater().inflate(R.menu.main, menu);
//		return true;
//	}
}
